from manim import *

# manim -qm -v WARNING QuadraticFunction.py
class QuadraticFunction(Scene):
    def construct(self):
        # 创建坐标轴
        axes = Axes(
            x_range=[-5, 5, 1],  # x 轴范围
            y_range=[-20, 20, 5],  # y 轴范围
            axis_config={"color": BLUE},
        )

        # 添加坐标轴标签
        axis_labels = axes.get_axis_labels(x_label="x", y_label="y")

        # 初始二次函数（系数 a = -10）
        a_value = -10
        quadratic_function = axes.plot(lambda x: a_value * x**2, color=YELLOW)

        # 添加函数标签
        function_label = MathTex("y = ax^2").next_to(axis_labels, UP*0.2)

        # 动态显示系数 a 的值
        a_label = DecimalNumber(
            a_value,
            num_decimal_places=1,
            include_sign=True,
            color=YELLOW
        )
        a_text = Text("a = ", color=YELLOW).next_to(a_label, LEFT)
        a_group = VGroup(a_text, a_label).next_to(function_label, DOWN)

        # 添加所有对象到场景
        self.play(Create(axes), Write(axis_labels))
        self.play(Create(quadratic_function), Write(function_label), Write(a_group))
        self.wait(1)

        # 动态更新二次函数的系数 a
        for a in np.arange(-10, 10.1, 0.1):  # 从 -10 到 10，步长 0.1
            new_function = axes.plot(lambda x: a * x**2, color=YELLOW)
            a_label.set_value(a)  # 更新系数显示
            self.play(
                Transform(quadratic_function, new_function),
                UpdateFromFunc(a_group, lambda m: m.next_to(function_label, DOWN)),
                rate_func=linear,
                run_time=0.05
            )

        # 保持显示
        self.wait(2)

# 运行脚本
if __name__ == "__main__":
    scene = QuadraticFunction()
    scene.render()